<script setup>
import { onMounted, reactive, ref, getCurrentInstance, computed } from "vue";
import { onLoad, onReachBottom } from "@dcloudio/uni-app";
import UQRCode from "uqrcodejs"; // npm install uqrcodejs
import { handleGoBack } from "@/utils/router";
import { promoCodeApi } from "@/services/login";
import { useUserStore } from "@/stores/user";
import CustomizeTopBar from "../../pages/components/customize-top-bar/CustomizeTopBar.vue";
import useFormat from "@/hooks/format";

const { formatPhone } = useFormat();

const userStore = useUserStore();
const userInfo = computed(() => userStore.userInfo);

// const user = useUserStore();
const statusBarHeight = ref(0);
const menuButtonInfo = ref(null);

// 获得当前组件实例
const instance = getCurrentInstance();

// 响应式数据
//兼容小程序
// #ifdef MP-WEIXIN
menuButtonInfo.value = uni.getMenuButtonBoundingClientRect();
// #endif
statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight;
const codeData = ref({
  imgURL: "",
  showcanvas: true,
});
// init data loading
const initDataLoading = ref(true);
// api得到的数据 展示
const showDetail = ref(undefined);

const APPsetImage = () => {
  if (codeData.value.imgURL) {
    return;
  }
  try {
    const codeValue = "532487";
    const qr = new UQRCode();
    // 设置二维码内容
    qr.data = codeValue;
    // 设置二维码大小，必须与canvas设置的宽高一致
    qr.size = 200;
    // 调用制作二维码方法
    qr.make();
    // 获取canvas上下文
    var canvasContext = uni.createCanvasContext("qrcode", instance); // 如果是组件，this必须传入
    // 设置uQRCode实例的canvas上下文
    qr.canvasContext = canvasContext;
    qr.drawCanvas();
    setTimeout(() => {
      uni.canvasToTempFilePath(
        {
          canvasId: "qrcode",
          success: (res) => {},
          complete: function (res) {
            codeData.value.imgURL = res.tempFilePath;
            //生成图片后隐藏标签 有时候会生成失败，或者弹窗显示图片后图片马上消失 多调试几次 代码没有问题的 研究一下是哪步需要小修改
            codeData.value.showcanvas = false;
          },
          fail: (err) => {},
        }
        // this // 组件内使用必传当前实例
      );
    }, 300);
  } catch (error) {}
};

// 保存到手机
const download = () => {
  // #ifdef H5
  let a = document.createElement("a");
  a.download = "";
  a.href = showDetail.value.qrcode;
  document.body.appendChild(a);
  a.click();
  a.remove();
  // #endif
  // #ifdef APP-PLUS || MP-WEIXIN
  wx.getImageInfo({
    src: showDetail.value.qrcode,
    success: (res) => {
      uni.saveImageToPhotosAlbum({
        filePath: res.path,
        success: () => {
          uni.showToast({
            title: "保存成功",
            icon: "success",
            duration: 1000,
          });
        },
        fail: (err) => {
          uni.showModal({
            title: "授权提示",
            content: "需要授权保存图片到相册",
            success: (res) => {
              if (res.confirm) {
                // 用户同意授权，重新请求授权
                uni.openSetting({
                  success() {
                    // 再次尝试保存图片
                    uni.saveImageToPhotosAlbum({
                      filePath: "图片路径",
                      success: () => {
                        console.log("图片保存成功");
                      },
                      fail: (err) => {
                        console.log("图片保存失败", err);
                      },
                    });
                  },
                  fail() {
                    // 用户拒绝授权
                    console.log("用户拒绝授权保存图片到相册");
                  },
                });
              }
            },
          });
        },
      });
    },
    fail: (err) => {
      uni.showToast({
        title: "保存失败!",
        icon: "error",
        duration: 2000,
      });
    },
  });
  // #endif
};

// go back
const goBack = () => {
  handleGoBack();
};

// init
const initData = async () => {
  try {
    initDataLoading.value = true;
    const results = await Promise.all([promoCodeApi()]);
    showDetail.value = results[0].data;
    initDataLoading.value = false;
    // APPsetImage();
  } catch (error) {
    initDataLoading.value = false;
  }
};

onMounted(() => {
  initData();
});
</script>

<template>
  <view class="my-content u-skeleton">
    <customize-top-bar title="我的推广码">
      <template v-slot:bgView>
        <view class="mycontent-top-bc"></view>
      </template>
    </customize-top-bar>

    <view class="container">
      <view class="business-card">
        <view class="business-card-info">
          <text class="name-text">{{ userInfo?.nickname || "-" }} </text>
          <text class="phone-text">{{
            (userInfo?.phone && formatPhone(userInfo?.phone)) || "-"
          }}</text>
        </view>
        <up-divider></up-divider>
        <view class="business-card-code">
          <up-copy :content="userInfo.promo_code || '-'">
            <view class="copy-warp">
              <text class="copy-text">
                <text class="bold-text">推广码 </text>：
                {{ userInfo.promo_code || "-" }}
              </text>
              <image src="@/static/copy-green.png" mode="widthFix" />
            </view>
          </up-copy>
          <view class="code-warp">
            <!-- #ifdef H5 -->
            <!-- h5端部分机型用uniappimg标签无法长按保存，用回原生img标签 -->
            <img
              class="code-data-image"
              :src="showDetail.qrcode"
              v-if="!initDataLoading"
            />
            <view v-else>
              <up-loading-icon></up-loading-icon>
            </view>
            <!-- #endif -->
            <!-- #ifdef APP-PLUS || MP-WEIXIN -->
            <image
              class="code-data-image"
              :src="showDetail.qrcode"
              mode="widthFix"
              v-if="!initDataLoading"
            ></image>
            <view v-else>
              <up-loading-icon></up-loading-icon>
            </view>
            <!-- #endif -->
          </view>
          <view class="description-text">扫一扫 成为我的客户</view>
          <view class="save-btn-warp">
            <!-- #ifdef H5 -->
            长按图片保存或分享
            <!-- #endif -->
            <!-- #ifdef APP-PLUS || MP-WEIXIN -->
            <up-button
              @click="download"
              shape="circle"
              text="保存到相册"
              v-if="!initDataLoading"
            ></up-button>
            <!-- #endif -->
          </view>
        </view>
      </view>
    </view>
  </view>

  <!-- 组件方式生成海报和二维码 -->
  <!-- <canvas
    ref="qrcode"
    id="qrcode"
    canvas-id="qrcode"
    style="width: 200px; height: 200px"
    v-show="codeData.showcanvas"
  ></canvas> -->
</template>

<style lang="scss" scoped>
@import "Index.scss";
</style>
